package se.webbzon.oschi01.action;

import java.awt.Component;
import java.awt.event.ActionEvent;

import javax.swing.Icon;
import javax.swing.JOptionPane;

import se.webbzon.oschi01.command.Command;
import se.webbzon.oschi01.gui.ApplicationIconSheet;
import se.webbzon.oschi01.gui.ApplicationIcon;
import se.webbzon.oschi01.nbt.Tag;
import se.webbzon.oschi01.singleton.Singletons;

public class NBTRenameAction extends DefaultAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -5460113495076267659L;

	private static final ApplicationIconSheet iconSheet = Singletons.instance(ApplicationIconSheet.class);

	private final Component parent;
	private final Tag<?> nbtTag;
	
	public NBTRenameAction(Component parent, Tag<?> nbtTag) {
		this.parent = parent;
		this.nbtTag = nbtTag;
		putValue(NAME, "Rename...");
		putValue(SMALL_ICON, iconSheet.getIcon(ApplicationIcon.Rename));	
	}

	@Override public void actionPerformed(ActionEvent e) {
		String message = "New tag name...";
		String title = "Rename";
		int messageType = JOptionPane.PLAIN_MESSAGE;
		Icon icon = iconSheet.getIcon(ApplicationIcon.Rename);
		String defaultValue = nbtTag.toString();
		Object value = JOptionPane.showInputDialog(parent, message, title, messageType, icon, null, defaultValue);
		if (value instanceof String && !value.equals(defaultValue))
			performCommand(new CommandImpl((String) value));
	}
	
	private final class CommandImpl implements Command {
		
		private final String newName;
		private final String oldName;
		
		public CommandImpl(String name) {
			this.newName = name;
			this.oldName = nbtTag.toString();
		}

		@Override public String getName() {
			return "rename \"" + oldName + "\" to \"" + newName + "\"";  
		}

		@Override public void redo() {
			nbtTag.setName(newName);
		}

		@Override public void undo() {
			nbtTag.setName(oldName);
		}
		
	}
	

}
